<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择入库仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-locationNo>
              <el-input
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择货位号"
                v-model="formInfo.data.locationNo"
              >
                <template #append>
                  <el-icon @click="selectShelfNo"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品</el-button
              >
            </template>
            <template v-slot:filter-productCodeScan>
              <ScanInputBox
                v-model:query="scanInfo.query"
                :api="scanInfo.api"
                :disabled="!canAddProduct"
                @callback="onCallBackScanData"
              />
            </template>
          </page-filter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="false"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-putQty="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.putQty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.putQty) }}</span
                    >
                  </template>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.putQty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <SelectDepotStorage
      v-if="selectDepotStorageInfo.visible"
      v-model:showDialog="selectDepotStorageInfo.visible"
      v-model:query="selectDepotStorageInfo.query"
      :excludeQueryList="selectDepotStorageInfo.excludeQueryList"
      :right-table-key="'putShelfTaskAddWmsStoreDetailsRigth-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO'"
      :left-table-key="'putShelfTaskAddWmsStoreDetailsLeft-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO'"
      :showPrice="$permission('putShelfTask:price')"
      @callback="selectDepotStorageCallBack"
    />

    <SelectDepot
      v-if="selectStoreDepotInfo.visible"
      v-model:showDialog="selectStoreDepotInfo.visible"
      :checkBox="false"
      v-model:query="selectStoreDepotInfo.query"
      :highlightRow="true"
      :checkLock="true"
      :saveEmpty="true"
      @callback="selectStoreDepotCallBack"
    />
    <SelectShelfNo
      v-if="selectShelfNoInfo.visible"
      v-model:showDialog="selectShelfNoInfo.visible"
      v-model:query="selectShelfNoInfo.query"
      :checkBox="false"
      :highlightRow="true"
      :checkLock="true"
      :saveEmpty="true"
      @callback="selectShelfNoCallBack"
    />

    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:leftQueryObj="individualInfo.leftQuery"
      v-model:rightQueryObj="individualInfo.rightQuery"
      v-model:infoList="individualInfo.productInfo"
      :requestRightList="!!tableRow.id"
      v-model:rightApi="individualInfo.rightApi"
      v-model:leftApi="individualInfo.leftApi"
      v-model:rightVo="individualInfo.rightVo"
      :leftTableKey="'putShelfTaskAddWmsStoreDetailsRigth-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO'"
      :showPrice="$permission('putShelfTask:price')"
      :scanInfo="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="putShelfTaskModify">
import {
  scanStoreStockOrderDetails,
  addAndPutShelfTask,
  getWsmStoreStockOrderDetailCustomizeList,
} from '@/api/wms'
import { getCustomizeSetting } from '@/api/customize'
import moment from 'moment'
import SelectDepotStorage from './selectDepotStorage'
import selectIndividual from './individual'
import ScanInputBox from './ScanInputBox'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId', 'tableRow'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const scanInfo = ref({
  api: scanStoreStockOrderDetails,
  query: {
    // queryMap: {
    //   isConsignBusiness: {
    //     queryType: "EQUALS",
    //     queryCategory: "AND",
    //     value: "",
    //   },
    // },
    // customizeUserVO: {},
    // queryParams: {
    //   // depotId: "",
    //   // validateExpire: false
    // },
    orderId: props.tableRow.id,
  },
})
const formRefs = ref([])
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    putShelfUser: -2,
  },
  fieldList: [
    {
      label: '来源单号',
      value: 'sourceOrderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'slot',
      require: true,
    },

    {
      label: '货位号',
      value: 'locationNo',
      type: 'slot',
      require: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    // putShelfUser: [
    //   { required: true, message: "请选择上架人", target: "change" },
    // ],
    depotName: [{ required: true, message: '请选择仓库', target: 'change' }],
    locationNo: [{ required: true, message: '请选择货位号', target: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'putQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.qtyFormatter },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectStoreDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    useTypeId: '1',
    status: 1,
  },
})
const selectShelfNoInfo = ref({
  visible: false,
  query: {
    depotId: null,
  },
})
const selectDepotStorageInfo = ref({
  //库存产品
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow.id,
    },
  },
})
const individualInfo = ref({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  rightApi: getWsmStoreStockOrderDetailCustomizeList, //个体弹窗右边数据接口
  leftApi: getWsmStoreStockOrderDetailCustomizeList, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canAddProduct = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.locationNo
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length && !tableInfo.value.isSysGroup) {
      tableInfo.value.data.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let putCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let putQty = proxy.$fn.accDiv(putCalcQty, unitConvertCoefficient)
        row['putCalcQty'] = putCalcQty
        row['putQty'] = putQty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(putCalcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].putQty = putQty
          row.details[0].putCalcQty = putCalcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})

createData()
function createData() {
  let obj = {
    putQty: {
      label: '数量',
      value: 'putQty',
      type: 'slot',
      minWidth: '250px',
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('putShelfTask:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('putShelfTask:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('putShelfTask:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    locationTypeValue: {
      label: '货位属性',
      value: 'locationTypeValue',
      asValue: 'locationType',
      componentType: 'select-model',
      code: 'goods_location_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getInvdividualRightCustomize()
}
function selectShelfNo() {
  //选择货位
  selectShelfNoInfo.value.query.depotId = formInfo.value.data.depotId
  selectShelfNoInfo.value.visible = true
}
function selectShelfNoCallBack(data) {
  if (data && data.id) {
    formInfo.value.data['locationNo'] = data.locationNo
  } else {
    formInfo.value.data['locationNo'] = ''
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(
      proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient) /
        row.unitConvertCoefficient
    )
  } else {
    return row.availableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient) /
      row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(
      proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient) %
        row.unitConvertCoefficient
    )
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient) /
      row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient) %
          row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.value.isSysGroup
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]
  let _tableInfo = tableInfo.value
  let key = []
  _tableInfo.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (_tableInfo.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(
        detail.groupConcatIds.toString()
      )
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = _tableInfo.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.groupConcatIds.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}
async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据
  let _tableInfo = tableInfo.value
  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStoragePutShelf(
      data,
      _tableInfo.sysGroup,
      _tableInfo.map,
      getWsmStoreStockOrderDetailCustomizeList,
      props.tableRow.id,
      individualInfo.value.rightVo,
      'scan'
    )
    _tableInfo.map = map
    _tableInfo.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = _tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
async function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data
  let _tableInfo = tableInfo.value
  if (_tableInfo.data && _tableInfo.data.length) {
    let items = _tableInfo.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatIds)
        let bool = arr.includes(detail.groupConcatIds.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(
            proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient),
            row.putCalcQty
          )
          if (num <= 1) {
            return (
              row.putCalcQty ===
              proxy.$fn.accMul(row.availableQty, row.unitConvertCoefficient)
            )
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStoragePutShelf(
    mergeDetail,
    _tableInfo.sysGroup,
    _tableInfo.map,
    getWsmStoreStockOrderDetailCustomizeList,
    props.tableRow.id,
    individualInfo.value.rightVo,
    'availableQty'
  )
  _tableInfo.map = map
  _tableInfo.data = [...map.values()]
  _tableInfo.data.forEach((item) => {
    item.groupConcatIds = item.details
      .map((row) => row.groupConcatIds)
      .toString()
  })
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.value.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  let _individualInfo = individualInfo.value
  for (let key in _individualInfo.selectObj) {
    _individualInfo.selectObj[key].value = data[key]
  }
  _individualInfo.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  _individualInfo.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  _individualInfo.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.value.data.depotId,
  }
  _individualInfo.leftQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.tableRow.id,
  }

  _individualInfo.leftQuery = {
    ..._individualInfo.leftQuery,
    ..._individualInfo.selectObj,
  }
  _individualInfo.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  _individualInfo.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.tableRow.id,
  }

  _individualInfo.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    let _tableInfo = tableInfo.value
    _tableInfo.map.set(data.key, data)
    let index = _tableInfo.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      _tableInfo.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
function getMain() {
  formInfo.value.data['depotId'] = props.tableRow.depotId
  formInfo.value.data['depotName'] = props.tableRow.depotName
  formInfo.value.data['remark'] = props.tableRow.remark
  formInfo.value.data['sourceOrderNo'] = props.tableRow.orderNo
  formInfo.value.data['sourceOrderId'] = props.tableRow.id
  // scanInfo.value.query.queryParams.depotId = props.tableRow.depotId;
  filterInfo.value.query.queryMap.orderId.value = props.tableRow.id
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
function save() {
  const _formInfo = formInfo.value
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = _tableInfo.data.filter((row) => row.productId)

    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    const data = _formInfo.data
    data.mergeDetails = _tableInfo.data
    const api = addAndPutShelfTask
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
//选择仓库
function selectStoreDepot() {
  selectStoreDepotInfo.value.visible = true
}
function selectStoreDepotCallBack(data = undefined) {
  let _formInfo = formInfo.value
  if (data && data.id) {
    _formInfo.data.depotId = data.id
    _formInfo.data.depotName = data.name
  } else {
    _formInfo.data.depotId = ''
    _formInfo.data.depotName = ''
  }
  tableInfo.value.data = []
  formInfo.value.data['locationNo'] = ''
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.value.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.value.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  // if (props.orderId) {
  //   selectDepotStorageInfo.value.query.isConsignBusiness.value =
  //     formInfo.value.data.isConsignBusiness;
  // }
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.value.query.depotId.value = formInfo.value.data.depotId
  selectDepotStorageInfo.value.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回
  let _tableInfo = tableInfo.value
  let map = await proxy.$fn.getDepotStoragePutShelf(
    rows,
    _tableInfo.sysGroup,
    _tableInfo.map,
    getWsmStoreStockOrderDetailCustomizeList, //个体弹窗右边数据接口
    props.tableRow.id,
    individualInfo.value.rightVo, //个体弹窗右边表格配置
    'availableQty'
  )
  _tableInfo.map = map
  _tableInfo.data = [...map.values()]
  _tableInfo.data.forEach((item) => {
    item.groupConcatIds = item.details
      .map((row) => row.groupConcatIds)
      .toString()
  })
}
//删除产品
function removeProduct(row = undefined) {
  let _tableInfo = tableInfo.value
  if (row && row.key) {
    _tableInfo.data = _tableInfo.data.filter((item) => item.key !== row.key)
    let key = row.key
    _tableInfo.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        _tableInfo.selections.forEach((row) => {
          for (let [key, value] of _tableInfo.map) {
            if (key === row.key) {
              _tableInfo.map.delete(key)
            }
          }
        })
        _tableInfo.data = tableInfo.value.data.filter((row) => {
          return !_tableInfo.selections.includes(row)
        })
      })
  }
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'addPutShelfTaskDetails-com.slip.spd.entity.vo.wms.WmsPutShelfTaskDetailVO',
  }
  _tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          _tableInfo.isSysGroup = true
        }
      }
      filterInfo.value.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'putShelfTaskAddWmsStoreDetailsLeft-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      if (res && res.success) {
        let data = res.data
        let arr = []
        let obj = {}
        if (tableInfo.value.isSysGroup) {
          for (let key in data.detail) {
            if (data.detail[key].sysGroupLevel > 0) {
              arr.push({
                columnName: data.detail[key].columnName,
                asTbName: data.detail[key].asTbName,
                key: key,
              })
              obj[key] = {
                queryType: 'EQUALS',
                queryCategory: 'AND',
                ignoreEmptyValue: false,
                value: null,
              }
            }
          }
        } else {
          arr.push({
            columnName: data.detail.id.columnName,
            asTbName: data.detail.id.asTbName,
            key: 'groupConcatIds',
          })
          obj['groupConcatIds'] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            value: null,
          }
        }
        // scanInfo.value.query.customizeUserVO = data;
        individualInfo.value.selectObj = obj
        _tableInfo.sysGroup = arr
        if (props.tableRow && props.tableRow.id) {
          getMain()
        }
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'putShelfTaskAddWmsStoreDetailsRigth-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.value.rightVo = res.data
    }
  })
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
